package com.linkage.seapeak.activity.register;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.QQAuthData;
import com.linkage.seapeak.pojo.WxAuthData;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BindPhoneActivity extends BaseWhiteActivity implements View.OnClickListener {

    private String openId;

    EditText et_username, et_vcode;
    TextView btn_login, getcode,tv_copy;
    MyCountDownTimer myCountDownTimer;
    CheckBox ck_read;
    private int type=1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Serializable data = getIntent().getSerializableExtra("data");
        if (data == null) {
            showToast("参数错误！");
            finish();
            return;
        }

        if (data instanceof QQAuthData) {
            openId = ((QQAuthData) data).getUserID();
            type = 1;
        } else if (data instanceof WxAuthData)
        {
            openId = ((WxAuthData) data).getOpenid();
            type=2;
        }else{
        return ;
        }

        setContentView(R.layout.activity_bind_phone, "绑定手机号");
        initview();
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        et_username = findViewById(R.id.et_username);
        btn_login = findViewById(R.id.btn_login);
        et_vcode = findViewById(R.id.et_vcode);
        getcode = findViewById(R.id.getcode);
        ck_read = findViewById(R.id.ck_read);

        tv_copy = findViewById(R.id.tv_copy);
        tv_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWeb("http://www.poxiao.com");
            }
        });
        btn_login.setOnClickListener(this);
        getcode.setOnClickListener(this);

        et_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showCode();
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        et_vcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showCode();
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        showCode();
        showSave();

        myCountDownTimer = new MyCountDownTimer(60000, 1000);
    }

    private void showCode()
    {
        String str1 =  et_username.getText().toString().trim();
        if(str1.equalsIgnoreCase(""))
        {
            getcode.setClickable(false);
            getcode.setTextColor(getResources().getColor(R.color.btnosel));
        }else{
            getcode.setClickable(true);
            getcode.setTextColor(getResources().getColor(R.color.btsel));
        }
    }

    private void showSave()
    {
        String str1 =  et_username.getText().toString().trim();
        String str2 =  et_vcode.getText().toString().trim();

        if(!str1.equalsIgnoreCase("") && !str2.equalsIgnoreCase("")
               )
        {

            btn_login.setClickable(true);
            btn_login.setBackgroundResource((R.drawable.login_corner_btn));
        }else{
            btn_login.setClickable(false);
            btn_login.setBackgroundResource((R.drawable.login_corner_nosel_btn));
        }


    }

    private int showWeb(String url) {
        int ret = -1;
        try {
            Uri uri = Uri.parse(url);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
            ret = 0;
        } catch (Exception e) {

        }
        return ret;
    }

    @Override
    public void onClick(View view) {
        String phone = "";
        String code = "";
        switch (view.getId()) {
            case R.id.btn_login:
                //返回
//                MainActivity.start(this);
//                finish();
                phone = et_username.getText().toString();
                code = et_vcode.getText().toString();
                if ("".equalsIgnoreCase(phone)) {
                    showToast("手机号码不能为空");
                    return;
                }
                if ("".equalsIgnoreCase(code)) {
                    showToast("验证码不能为空");
                    return;
                }
                if(!ck_read.isChecked())
                {
                    showToast("请阅读并同意《平台服务协议》");
                    return;
                }

                bindUser(phone, code);
                break;
            case R.id.getcode:
                phone = et_username.getText().toString();
                if ("".equalsIgnoreCase(phone)) {
                    showToast("手机号码不能为空");
                    return;
                } else {

                    getSMSCode(phone);

                }
                break;
            default:
                break;
        }
    }

    /**
     * 手机号	mobile	String	是
     * 短信验证码	smsCaptha	String	是
     * openid	openid	String	是
     * 绑定类型	type	int	是	1.qq绑定; 2.微信绑定
     *
     * @param mobile
     * @param code
     */
    private void bindUser(String mobile, String code) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        showProgress();
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = getTokenRequest()
                .add("mobile", mobile)
                .add("smsCaptha", code)
                .add("openid", openId)
                .add("type", type+"")
                .build();

        String url = Consts.WEBURL_BIND_USER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
                hideProgress();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                final String str = response.body().string();
                Log.i(TAG, "onResponse: " + str);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgress();
                        try {
                            JSONObject object = new JSONObject(str);
                            if(object.optInt("code")==0) {
                                JSONObject info = object.getJSONObject("data");
                                if (info != null) {
                                    LoginInfo userInfo = new Gson().fromJson(info.getString("userInfo"), LoginInfo.class);
//                                Hawk.put(HawkKey.USERTOKEN, info.getString("userToken"));
//                                Hawk.put(HawkKey.LOGINDETIAL, userInfo);
                                    BankruptcyApp.userToken = info.getString("userToken");

                                    BankruptcyApp.loginInfo = userInfo;
                                    SPUtils.getInstance(Consts.SPNAME).put("userInfo", object.getString("data"));
                                    SPUtils.getInstance(Consts.SPNAME).put("userToken", info.getString("userToken"));
                                    SPUtils.getInstance(Consts.SPNAME).put("userId", userInfo.getId());
                                    finish();
                                }else{
                                    showToast("数据获取异常");
                                }
                            } else if(object.optInt("code")==107)
                            {
                                noticeDialog = new PublicNoticeDialog(BindPhoneActivity.this,onClickListener,
                                        1,"提示","该手机已绑定其他账号？",
                                        "取消","手机号登录");
                                noticeDialog.show();
                            }else{
                                showToast("提交失败"+object.optString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }
    private PublicNoticeDialog noticeDialog;

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();
//                    finish();
                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();
//                    finish();
                    break;

                case R.id.btn_save_notice:
                    PhoneLoginActivity.start(BindPhoneActivity.this);
                    finish();
                    noticeDialog.dismiss();
                    break;

            }
        }
    };


    public void getSMSCode(final String mobile) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        showProgress();


        Observable<JsonObject> observable  ;

            observable = Network
                    .getAPIService()
                    .getSMSCode(mobile,1);


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        hideProgress();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {

                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TASK);
                        EventBus.getDefault().post(event);
                        myCountDownTimer.start();
                        showToast("提交成功"+json.get("data"));
//                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        super.onError(e);
                    }
                });



    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getcode.setClickable(false);
            getcode.setText(l / 1000 + "秒");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getcode.setText("重新获取");
            //设置可点击
            getcode.setClickable(true);
        }
    }
}
